package cn.ihrm.sass.controller;

import cn.common.Result;
import cn.common.ResultCode;
import cn.exception.CommonException;
import cn.ihrm.sass.entity.company.Company;
import cn.ihrm.sass.service.CompanyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//解决跨域问题
@CrossOrigin
@Api(description = "企业管理",value = "CompanyController")
@RestController
@RequestMapping(value = "/company")
public class CompanyController {

    @Autowired
    private CompanyService companyService;

    /**
     * 保存企业
     * @param company
     * @return
     */
    @ApiOperation(value = "保存企业")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Result save(@RequestBody Company company) {
        //业务操作
        companyService.add(company);
        //return new Result(ResultCode.SUCCESS);
        return new Result(10000,"操作成功！",true);
    }

    /**
     * 根据id更新企业
     * 1.方法
     * 2.请求参数
     * 3.响应
     */
    @ApiOperation(value = "根据id更新企业")
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@PathVariable(value = "id") String id, @RequestBody Company company) {
        //业务操作
        company.setId(id);
        companyService.update(company);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据id删除企业
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id删除企业")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable(value = "id") String id) {
        companyService.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据id查询企业
     * @param id
     * @return
     * @throws CommonException
     */
    @ApiOperation(value = "根据id查询企业")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable(value = "id") String id) throws CommonException {

        Company company = companyService.findById(id);
        Result result = new Result(ResultCode.SUCCESS);
        result.setData(company);
        return result;


        //throw new CommonException(ResultCode.UNAUTHORISE);
    }

    /**
     * 查询全部企业列表
     * @return
     */
    @ApiOperation(value = "查询全部企业列表")
    @RequestMapping(value = "findAll", method = RequestMethod.GET)
    public Result findAll() {
        //int i = 1 / 0;
        List<Company> list = companyService.findAll();
        //返回对象
        Result result = new Result(ResultCode.SUCCESS);
        result.setData(list);
        return result;
    }
}
